package com.zzb.projectfactory.framework.utils;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlExportParameterVisitor;
import com.alibaba.druid.sql.visitor.ExportParameterVisitor;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.fastjson.JSON;

import java.util.List;

/**
 * sql去参数
 * Created by zzb on 17-3-9.
 */
public class SQLUtils {
    public static String getSqlWithoutParam(String sql){
        try {
            List<SQLStatement> stmtLista = com.alibaba.druid.sql.SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
            StringBuilder out = new StringBuilder();
            ExportParameterVisitor visitor = new MySqlExportParameterVisitor(out);
            for (SQLStatement stmt : stmtLista) {
                stmt.accept(visitor);
            }
            return out.toString();
        } catch (Exception e) {
            return sql;
        }
    }
    public static boolean sqlIsValid(String sql){
        try {
            List<SQLStatement> stmtLista = com.alibaba.druid.sql.SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
            StringBuilder out = new StringBuilder();
            ExportParameterVisitor visitor = new MySqlExportParameterVisitor(out);
            for (SQLStatement stmt : stmtLista) {
                stmt.accept(visitor);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }


}
